package com.may._7;

import java.util.concurrent.*;

public class MyThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(2,//常驻线程数
                5,//最大线程数
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),//队列任务数
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t 处理任务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }

    public static void threadPoolInit() {
        //System.out.println(Runtime.getRuntime().availableProcessors());//查看计算器 cpu 核数

        //ExecutorService threadPool = Executors.newFixedThreadPool(5);//一池，5个处理线程
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池1个处理线程
        ExecutorService threadPool = Executors.newCachedThreadPool();//一池 n 线程

        //模拟10个任务，用5个线程处理
        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t 处理任务");
                });
                //try { TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();//线程不用开启，但记得关闭
        }
    }
}
